import { getInfo, login, logout } from '@/api/login'
import config from '@/config'
import defAva from '@/static/images/profile.jpg'
import { getToken, removeToken, setToken } from '@/utils/auth'
import constant from '@/utils/constant'
import storage from '@/utils/storage'
import { isEmpty, isHttp } from '@/utils/validate'
// src/store/user.js
import { defineStore } from 'pinia'
import { ref } from 'vue'

const baseUrl = config.baseUrl

export const useUserStore = defineStore('user', () => {
  // state
  const token = ref(getToken())
  const id = ref(storage.get(constant.id))
  const name = ref(storage.get(constant.name))
  const avatar = ref(storage.get(constant.avatar))
  const roles = ref(storage.get(constant.roles) || [])
  const permissions = ref(storage.get(constant.permissions) || [])

  // actions
  function setTokenAction(newToken) {
    token.value = newToken
    setToken(newToken)
  }

  function setId(newId) {
    id.value = newId
    storage.set(constant.id, newId)
  }

  function setName(newName) {
    name.value = newName
    storage.set(constant.name, newName)
  }

  function setAvatar(newAvatar) {
    avatar.value = newAvatar
    storage.set(constant.avatar, newAvatar)
  }

  function setRoles(newRoles) {
    roles.value = newRoles
    storage.set(constant.roles, newRoles)
  }

  function setPermissions(newPermissions) {
    permissions.value = newPermissions
    storage.set(constant.permissions, newPermissions)
  }

  // 登录
  function loginAction(userInfo) {
    const username = userInfo.username.trim()
    const password = userInfo.password
    const code = userInfo.code
    const uuid = userInfo.uuid
    return new Promise((resolve, reject) => {
      login(username, password, code, uuid)
        .then((res) => {
          setTokenAction(res.token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 获取用户信息
  function getInfoAction() {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((res) => {
          const user = res.user || {}
          let userAvatar = user.avatar || ''
          if (!isHttp(userAvatar)) {
            userAvatar = isEmpty(userAvatar) ? defAva : baseUrl + userAvatar
          }
          const userId = isEmpty(user) || isEmpty(user.userId) ? '' : user.userId
          const userName = isEmpty(user) || isEmpty(user.userName) ? '' : user.userName

          if (res.roles && res.roles.length > 0) {
            setRoles(res.roles)
            setPermissions(res.permissions)
          }
          else {
            setRoles(['ROLE_DEFAULT'])
          }
          setId(userId)
          setName(userName)
          setAvatar(userAvatar)
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 退出系统
  function logoutAction() {
    return new Promise((resolve, reject) => {
      logout(token.value)
        .then(() => {
          setTokenAction('')
          setRoles([])
          setPermissions([])
          removeToken()
          storage.clean()
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  return {
    // state
    token,
    id,
    name,
    avatar,
    roles,
    permissions,

    // actions
    loginAction,
    getInfoAction,
    logoutAction,
  }
})
